package com.xingfutong.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingfutong.common.utils.PageUtils;
import com.xingfutong.common.utils.Query;

import com.xingfutong.mall.product.dao.CategoryDao;
import com.xingfutong.mall.product.entity.CategoryEntity;
import com.xingfutong.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getTree() {
        //1.查出所有分类数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.筛选出所有子分类
        //2.1 所有一级分类数据筛选
        List<CategoryEntity> level1 = categoryEntities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((childrenMenu) -> {
            childrenMenu.setChildren(getChildren(childrenMenu, categoryEntities));
            return childrenMenu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1;
    }

    //递归筛选所有子分类
    private List<CategoryEntity> getChildren(CategoryEntity current, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> categorys = categoryEntities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == current.getCatId();
        }).map((categoryEntity) -> {
            categoryEntity.setChildren(getChildren(categoryEntity, categoryEntities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return categorys;
    }
}